﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DataStuctureStudy.Queues
{
    public class PriorityQueue<T>
        where T : IComparable<T>
    {
        private readonly int _maxSize;
        private readonly T[] _items;
        private int _count = 0;
        private int _head = -1;

        public PriorityQueue(int size)
        {
            _maxSize = size;
            _items = new T[size];
        }

        public void EnQueue(T item)
        {
            if (this.IsFull())
            {
                throw new InvalidOperationException("队列已满");
            }

            if (_count == 0)
            {
                _items[++_head] = item;
            }
            else
            {
                for (var i = _head; i >= 0; i++)
                {
                    if (_items[i].CompareTo(item) > 0)
                    {
                        _items[i + 1] = _items[i];
                    }
                    else
                    {
                        _items[i + 1] = item;
                        break;
                    }
                }
                _head++;
            }

            _count++;
        }

        public T DeQueue()
        {
            if (this.IsEmpty())
            {
                throw new InvalidOperationException("队列已空");
            }

            T item = _items[_head--];

            _count--;

            return item;
        }

        public T Peek()
        {
            if (this.IsEmpty())
            {
                throw new InvalidOperationException("队列已空");
            }

            return _items[_head];
        }

        public bool IsFull()
        {
            return _count == _maxSize;
        }

        public bool IsEmpty()
        {
            return _count == 0;
        }

        public int Size()
        {
            return _count;
        }

        private static void Swap(T[] items, int left, int right)
        {
            if (left != right)
            {
                var temp = items[left];
                items[left] = items[right];
                items[right] = temp;
            }
        }
    }
}
